package work.parabola.keyboardswitch.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.parabola.keyboardswitch.common.ResponseCode;
import work.parabola.keyboardswitch.common.ServerResponse;
import work.parabola.keyboardswitch.dao.ManufacturerDoMapper;
import work.parabola.keyboardswitch.pojo.query.manufacturer.AddManuQuery;
import work.parabola.keyboardswitch.pojo.query.manufacturer.ListQuery;
import work.parabola.keyboardswitch.pojo.repository.ManufacturerDo;
import work.parabola.keyboardswitch.pojo.vo.manufacturer.ManufacturerListVo;
import work.parabola.keyboardswitch.service.IManufacturerService;

import java.util.ArrayList;
import java.util.List;

@Service
public class ManufacturerServiceImpl implements IManufacturerService {

    @Autowired
    private ManufacturerDoMapper manufacturerDoMapper;

    @Override
    public ServerResponse add(AddManuQuery addManuQuery) {
        if (addManuQuery == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        ServerResponse response = addManuQuery.validate();
        if (!response.isSuccess()) {
            return response;
        }
        ManufacturerDo manufacturerDo = new ManufacturerDo();
        manufacturerDo.setName(addManuQuery.getName());
        manufacturerDo.setEnglishName(addManuQuery.getEnglishName());
        int rowCount = this.manufacturerDoMapper.insertSelective(manufacturerDo);
        if(rowCount == 0){
            return ServerResponse.createByErrorMessage("新增厂商失败");
        }
        return ServerResponse.createBySuccessMessage("新增厂商成功");
    }

    @Override
    public ServerResponse getManufacturerList(ListQuery listQuery) {
        if(listQuery == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        ServerResponse response = listQuery.validate();
        if(!response.isSuccess()){
            return response;
        }
        List<ManufacturerDo> manufacturerDoList = this.manufacturerDoMapper.selectByParams(listQuery.getSearchWord());
        List<ManufacturerListVo> manufacturerListVoList = new ArrayList<>();

        for(ManufacturerDo manufacturerDo: manufacturerDoList){
            ManufacturerListVo vo = new ManufacturerListVo();
            vo.setId(manufacturerDo.getId());
            vo.setName(manufacturerDo.getName());
            vo.setEnglishName(manufacturerDo.getEnglishName());
            vo.setIcon(manufacturerDo.getIcon());
            manufacturerListVoList.add(vo);
        }
        return ServerResponse.createBySuccess(manufacturerListVoList);
    }
}
